<template>
  <div class="page-container">
    <div class="d-flex justify-content-between align-items-center mb-4">
      <h2>项目管理</h2>
      <button class="btn btn-primary" @click="navigateToCreate">
        <i class="bi bi-plus-circle me-1"></i> 新建项目
      </button>
    </div>

    <!-- 项目筛选 -->
    <div class="card mb-4">
      <div class="card-body">
        <!-- 基础筛选 -->
        <div class="row g-3">
          <div class="col-md-3">
            <label class="form-label">项目名称</label>
            <input type="text" class="form-control" placeholder="搜索项目名称" v-model="filters.name">
          </div>
          <div class="col-md-3">
            <label class="form-label">工程代号</label>
            <input type="text" class="form-control" placeholder="搜索工程代号" v-model="filters.projectCode">
          </div>
          <div class="col-md-3">
            <label class="form-label">规划类型</label>
            <input type="text" class="form-control" placeholder="搜索规划类型" v-model="filters.planningType">
          </div>
          <div class="col-md-3">
            <label class="form-label">建设地点</label>
            <input type="text" class="form-control" placeholder="搜索建设地点" v-model="filters.location">
          </div>
          <div class="col-md-3">
            <label class="form-label">项目状态</label>
            <select class="form-select" v-model="filters.phaseStatus">
              <option value="">全部状态</option>
              <option v-for="status in phaseStatusOptions" :key="status" :value="status">{{ status }}</option>
            </select>
          </div>
          <div class="col-md-3">
            <label class="form-label">项目阶段</label>
            <select class="form-select" v-model="filters.status">
              <option value="">全部阶段</option>
              <option v-for="phase in phaseOptions" :key="phase.value" :value="phase.value">{{ phase.label }}</option>
            </select>
          </div>
          <div class="col-md-3">
            <label class="form-label">建设类型</label>
            <select class="form-select" v-model="filters.constructionType">
              <option value="">全部类型</option>
              <option value="统建">统建</option>
              <option value="代建">代建</option>
            </select>
          </div>
          <div class="col-md-3">
            <label class="form-label">使用单位类型</label>
            <select class="form-select" v-model="filters.usingUnitType">
              <option value="">全部类型</option>
              <option value="中心及下属单位">中心及下属单位</option>
              <option value="代供单位">代供单位</option>
              <option value="其他">其他</option>
            </select>
          </div>
          <div class="col-md-3 d-flex align-items-end">
            <button class="btn btn-primary w-100" @click="applyFilters">
              <i class="bi bi-search me-1"></i> 搜索
            </button>
          </div>
          <div class="col-md-3 d-flex align-items-end">
            <button class="btn btn-outline-secondary w-100" @click="toggleAdvancedFilters">
              <i class="bi" :class="showAdvancedFilters ? 'bi-chevron-up' : 'bi-chevron-down'"></i>
              {{ showAdvancedFilters ? '收起高级筛选' : '展开高级筛选' }}
            </button>
          </div>
        </div>
        
        <!-- 高级筛选 -->
        <div v-if="showAdvancedFilters" class="row g-3 mt-2 pt-3 border-top">
          <div class="col-md-3">
            <label class="form-label">投资规模</label>
            <select class="form-select" v-model="filters.investmentRange">
              <option value="">全部规模</option>
              <option value="0-500">小于500万</option>
              <option value="500-3000">500-3000万</option>
              <option value="3000-5000">3000-5000万</option>
              <option value="5000+">5000万以上</option>
            </select>
          </div>
          <div class="col-md-3">
            <label class="form-label">开始日期范围</label>
            <div class="input-group">
              <input type="date" class="form-control" v-model="filters.startDateFrom" placeholder="起始日期">
              <span class="input-group-text">至</span>
              <input type="date" class="form-control" v-model="filters.startDateTo" placeholder="结束日期">
            </div>
          </div>
          <div class="col-md-3">
            <label class="form-label">计划完成日期范围</label>
            <div class="input-group">
              <input type="date" class="form-control" v-model="filters.endDateFrom" placeholder="起始日期">
              <span class="input-group-text">至</span>
              <input type="date" class="form-control" v-model="filters.endDateTo" placeholder="结束日期">
            </div>
          </div>
          <div class="col-md-3">
            <label class="form-label">设计单位</label>
            <input type="text" class="form-control" placeholder="搜索设计单位" v-model="filters.designUnit">
          </div>
          <div class="col-md-3">
            <label class="form-label">施工单位</label>
            <input type="text" class="form-control" placeholder="搜索施工单位" v-model="filters.constructionUnit">
          </div>
          <div class="col-md-3">
            <label class="form-label">使用单位</label>
            <input type="text" class="form-control" placeholder="搜索使用单位" v-model="filters.usingUnit">
          </div>
          <div class="col-md-3">
            <label class="form-label">发包模式</label>
            <input type="text" class="form-control" placeholder="搜索发包模式" v-model="filters.biddingMode">
          </div>
          <div class="col-md-3">
            <label class="form-label">任务书文号</label>
            <input type="text" class="form-control" placeholder="搜索任务书文号" v-model="filters.taskDocumentNo">
          </div>
          <div class="col-md-3">
            <label class="form-label">要求完成时限</label>
            <div class="input-group">
              <input type="date" class="form-control" v-model="filters.requiredCompletionDateFrom" placeholder="开始日期">
              <span class="input-group-text">至</span>
              <input type="date" class="form-control" v-model="filters.requiredCompletionDateTo" placeholder="结束日期">
            </div>
          </div>
          <div class="col-12 d-flex justify-content-end mt-3">
            <button class="btn btn-outline-secondary me-2" @click="resetFilters">
              <i class="bi bi-arrow-counterclockwise me-1"></i> 重置筛选
            </button>
            <button class="btn btn-primary" @click="applyFilters">
              <i class="bi bi-search me-1"></i> 应用筛选
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 项目列表 -->
    <div class="card flex-grow-1 d-flex flex-column">
      <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="card-title mb-0">项目列表</h5>
        <div class="batch-actions" v-if="selectedProjects.length > 0">
          <span class="me-2">已选择 {{ selectedProjects.length }} 个项目</span>
          <button class="btn btn-sm btn-outline-primary me-2" @click="exportSelectedProjects">
            <i class="bi bi-file-earmark-excel me-1"></i>导出所选项目
          </button>
          <button class="btn btn-sm btn-outline-secondary" @click="clearSelection">
            <i class="bi bi-x-circle me-1"></i>清除选择
          </button>
        </div>
      </div>
      <div class="card-body d-flex flex-column p-0">
        <div class="table-responsive flex-grow-1">
          <table class="table table-hover w-100 mb-0">
            <thead>
              <tr>
                <th scope="col" width="4%">
                  <div class="form-check">
                    <input class="form-check-input" type="checkbox" 
                           :checked="isAllSelected" 
                           @change="toggleAllSelection" 
                           id="selectAllCheckbox">
                    <label class="form-check-label" for="selectAllCheckbox"></label>
                  </div>
                </th>
                <th scope="col" width="6%">项目序号</th>
                <th scope="col" width="16%">项目名称</th>
                <th scope="col" width="8%">工程代号</th>
                <th scope="col" width="8%">建设地点</th>
                <th scope="col" width="8%">建设类型</th>
                <th scope="col" width="10%">任务书下达时间</th>
                <th scope="col" width="10%">要求完成时限</th>
                <th scope="col" width="7%">总投资(万)</th>
                <th scope="col" width="7%">项目阶段</th>
                <th scope="col" width="6%">状态</th>
                <th scope="col" width="14%">操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(project, index) in displayedProjects" :key="project.id" 
                  class="project-row" 
                  @click="navigateToDetail(project.id, $event)">
                <td class="checkbox-cell" @click.stop>
                  <div class="form-check">
                    <input class="form-check-input" type="checkbox" 
                           :checked="isProjectSelected(project.id)"
                           @change="toggleProjectSelection(project)"
                           :id="`project-${project.id}`">
                    <label class="form-check-label" :for="`project-${project.id}`"></label>
                  </div>
                </td>
                <td>{{ project.project_number || '-' }}</td>
                <td>{{ project.name }}</td>
                <td>{{ project.project_code }}</td>
                <td>{{ project.location ? project.location.split(',')[0] : '-' }}</td>
                <td>{{ project.construction_type || '-' }}</td>
                <td>{{ project.task_issue_date || '-' }}</td>
                <td>{{ project.required_completion_date || '-' }}</td>
                <td>{{ project.total_investment ? project.total_investment.toLocaleString() : '-' }}</td>
                <td>
                  <span class="badge" :class="getPhaseClass(project)">
                    {{ getPhaseLabel(project.status) }}
                  </span>
                </td>
                <td>
                  <span class="badge" :class="getStatusClass(project)">{{ project.phase_status || '正常进行' }}</span>
                </td>
                <td class="action-cell">
                  <div class="action-buttons">
                    <button class="btn btn-success action-btn" @click.stop="editProject(project)">
                      <i class="bi bi-pencil me-1"></i>编辑
                    </button>
                    <button class="btn btn-danger action-btn" @click.stop="confirmDelete(project)">
                      <i class="bi bi-trash me-1"></i>删除
                    </button>
                  </div>
                </td>
              </tr>
              <tr v-if="displayedProjects.length === 0">
                <td colspan="11" class="text-center py-4">暂无项目数据</td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页 -->
        <div class="p-3 border-top">
          <nav aria-label="Page navigation">
            <ul class="pagination justify-content-center mb-0">
              <li class="page-item" :class="{ disabled: currentPage === 1 }">
                <a class="page-link" href="#" @click.prevent="changePage(currentPage - 1)" tabindex="-1" :aria-disabled="currentPage === 1">上一页</a>
              </li>
              <li v-for="page in totalPages" :key="page" class="page-item" :class="{ active: page === currentPage }">
                <a class="page-link" href="#" @click.prevent="changePage(page)">{{ page }}</a>
              </li>
              <li class="page-item" :class="{ disabled: currentPage === totalPages }">
                <a class="page-link" href="#" @click.prevent="changePage(currentPage + 1)" :aria-disabled="currentPage === totalPages">下一页</a>
              </li>
            </ul>
          </nav>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'

// 获取router实例
const router = useRouter()

// 项目数据
const allProjects = ref([])
const loading = ref(true)
const selectedProjects = ref([])

// 筛选条件
const filters = ref({
  name: '',
  projectCode: '',
  projectNumber: '',
  location: '',
  status: '',
  phaseStatus: '',
  investmentRange: '',
  startDateFrom: '',
  startDateTo: '',
  endDateFrom: '',
  endDateTo: '',
  designUnit: '',
  constructionUnit: '',
  usingUnit: '',
  biddingMode: '',
  taskDocumentNo: '',
  planningType: '',
  constructionType: '',
  requiredCompletionDateFrom: '',
  requiredCompletionDateTo: '',
  usingUnitType: ''
})

// 分页
const currentPage = ref(1)
const pageSize = ref(10)

// 项目阶段选项
const phaseOptions = [
  { value: '前期-', label: '前期' },
  { value: '发包-', label: '发包' },
  { value: '施工-', label: '施工' },
  { value: '竣工-', label: '竣工' }
]

// 项目状态选项
const phaseStatusOptions = ref(['正常进行', '阶段性迟缓', '滞后'])

// 高级筛选显示控制
const showAdvancedFilters = ref(false)

// 获取项目数据
async function fetchProjects() {
  try {
    loading.value = true
    const response = await window.api.database.getProjects()
    
    if (response.success) {
      allProjects.value = response.data
    } else {
      console.error('获取项目列表失败:', response.error)
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取系统设置
async function fetchSettings() {
  try {
    const response = await window.api.database.getSettings('project')
    
    if (response.success) {
      const phaseStatusSetting = response.data.find(item => item.key === 'default_phase_status')
      if (phaseStatusSetting && phaseStatusSetting.value) {
        phaseStatusOptions.value = phaseStatusSetting.value.split(',')
      }
    }
  } catch (error) {
    console.error('获取系统设置失败:', error)
  }
}

// 应用筛选
function applyFilters() {
  currentPage.value = 1
}

// 过滤后的项目
const filteredProjects = computed(() => {
  return allProjects.value.filter(project => {
    // 项目名称筛选
    if (filters.value.name && !project.name.includes(filters.value.name)) {
      return false
    }
    
    // 工程代号筛选
    if (filters.value.projectCode && project.project_code && 
        !project.project_code.toLowerCase().includes(filters.value.projectCode.toLowerCase())) {
      return false
    }
    
    // 项目编号筛选
    if (filters.value.projectNumber && project.project_number !== undefined) {
      const projectNumberStr = project.project_number.toString()
      if (!projectNumberStr.includes(filters.value.projectNumber)) {
        return false
      }
    } else if (filters.value.projectNumber) {
      return false
    }
    
    // 建设地点筛选
    if (filters.value.location && project.location && 
        !project.location.toLowerCase().includes(filters.value.location.toLowerCase())) {
      return false
    }
    
    // 项目阶段筛选
    if (filters.value.status && !project.status.startsWith(filters.value.status)) {
      return false
    }
    
    // 项目状态筛选
    if (filters.value.phaseStatus) {
      const selectedStatus = filters.value.phaseStatus;
      const projectStatus = project.phase_status || '正常进行';  // 如果状态为空，默认为"正常进行"
      
      console.log('筛选状态:', selectedStatus);
      console.log('项目状态:', projectStatus);
      
      if (selectedStatus !== projectStatus) {
        return false;
      }
    }
    
    // 投资规模筛选
    if (filters.value.investmentRange) {
      if (!project.total_investment) {
        return false; // 如果项目没有投资金额，则不显示
      }
      const investment = project.total_investment;
      switch (filters.value.investmentRange) {
        case '0-500':
          if (investment >= 500) return false;
          break;
        case '500-3000':
          if (investment < 500 || investment >= 3000) return false;
          break;
        case '3000-5000':
          if (investment < 3000 || investment >= 5000) return false;
          break;
        case '5000+':
          if (investment < 5000) return false;
          break;
      }
    }
    
    // 开始日期范围筛选
    const startDate = project.contract_start_date || project.task_issue_date
    if (filters.value.startDateFrom && startDate && startDate < filters.value.startDateFrom) {
      return false
    }
    if (filters.value.startDateTo && startDate && startDate > filters.value.startDateTo) {
      return false
    }
    
    // 计划完成日期范围筛选
    const endDate = project.contract_end_date || project.required_completion_date
    if (filters.value.endDateFrom && endDate && endDate < filters.value.endDateFrom) {
      return false
    }
    if (filters.value.endDateTo && endDate && endDate > filters.value.endDateTo) {
      return false
    }
    
    // 设计单位筛选
    if (filters.value.designUnit && project.design_unit && 
        !project.design_unit.includes(filters.value.designUnit)) {
      return false
    }
    
    // 施工单位筛选
    if (filters.value.constructionUnit && project.construction_unit && 
        !project.construction_unit.includes(filters.value.constructionUnit)) {
      return false
    }
    
    // 使用单位筛选
    if (filters.value.usingUnit && project.using_unit && 
        !project.using_unit.includes(filters.value.usingUnit)) {
      return false
    }
    
    // 使用单位类型筛选
    if (filters.value.usingUnitType && project.using_unit_type !== filters.value.usingUnitType) {
      return false
    }
    
    // 发包模式筛选
    if (filters.value.biddingMode && project.bidding_mode && 
        !project.bidding_mode.toLowerCase().includes(filters.value.biddingMode.toLowerCase())) {
      return false
    }
    
    // 任务书文号筛选
    if (filters.value.taskDocumentNo && project.task_document_no && 
        !project.task_document_no.includes(filters.value.taskDocumentNo)) {
      return false
    }
    
    // 规划类型筛选
    if (filters.value.planningType && project.planning_type && 
        !project.planning_type.toLowerCase().includes(filters.value.planningType.toLowerCase())) {
      return false
    }
    
    // 建设类型筛选
    if (filters.value.constructionType) {
      if (!project.construction_type || project.construction_type.trim() !== filters.value.constructionType.trim()) {
        return false
      }
    }
    
    // 要求完成时限筛选
    if (filters.value.requiredCompletionDateFrom && project.required_completion_date && 
        project.required_completion_date < filters.value.requiredCompletionDateFrom) {
      return false
    }
    if (filters.value.requiredCompletionDateTo && project.required_completion_date && 
        project.required_completion_date > filters.value.requiredCompletionDateTo) {
      return false
    }
    
    return true
  })
})

// 当前页显示的项目
const displayedProjects = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredProjects.value.slice(start, end)
})

// 总页数
const totalPages = computed(() => {
  return Math.max(1, Math.ceil(filteredProjects.value.length / pageSize.value))
})

// 切换页码
function changePage(page) {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
  }
}

// 获取进度条样式
function getProgressClass(project) {
  if (project.phase_status === '滞后') {
    return 'bg-danger'
  } else if (project.phase_status === '阶段性迟缓') {
    return 'bg-warning'
  } else if (project.progress >= 100) {
    return 'bg-success'
  } else {
    return 'bg-info'
  }
}

// 获取状态标签样式
function getStatusClass(project) {
  if (project.phase_status === '滞后') {
    return 'bg-danger'
  } else if (project.phase_status === '阶段性迟缓') {
    return 'bg-warning'
  } else {
    return 'bg-success'
  }
}

// 获取项目阶段标签
function getPhaseLabel(status) {
  if (status.startsWith('前期-')) {
    return '前期'
  } else if (status.startsWith('发包-')) {
    return '发包'
  } else if (status.startsWith('施工-')) {
    return '施工'
  } else if (status.startsWith('竣工-')) {
    return '竣工'
  } else {
    return status
  }
}

// 获取项目阶段样式
function getPhaseClass(project) {
  if (project.status.startsWith('前期-')) {
    return 'bg-info'
  } else if (project.status.startsWith('发包-')) {
    return 'bg-primary'
  } else if (project.status.startsWith('施工-')) {
    return 'bg-warning text-dark'
  } else if (project.status.startsWith('竣工-')) {
    return 'bg-success'
  } else {
    return 'bg-secondary'
  }
}

// 导航到项目详情页
function navigateToDetail(projectId, event) {
  // 如果点击的是操作按钮区域，不执行跳转
  if (event.target.closest('.action-cell')) {
    return
  }
  router.push(`/project-detail/${projectId}`)
}

// 导航到新建项目页面
function navigateToCreate() {
  router.push('/project-create')
}

// 编辑项目
function editProject(project) {
  router.push(`/project-edit/${project.id}`)
}

// 确认删除项目
function confirmDelete(project) {
  if (confirm(`确定要删除项目"${project.name}"吗？此操作不可恢复。`)) {
    console.log('删除项目:', project.id)
    // TODO: 实现删除项目功能
  }
}

// 选择相关方法
const isAllSelected = computed(() => {
  return displayedProjects.value.length > 0 && 
         displayedProjects.value.every(project => isProjectSelected(project.id))
})

function isProjectSelected(projectId) {
  return selectedProjects.value.some(p => p.id === projectId)
}

function toggleProjectSelection(project) {
  if (isProjectSelected(project.id)) {
    selectedProjects.value = selectedProjects.value.filter(p => p.id !== project.id)
  } else {
    selectedProjects.value.push(project)
  }
}

function toggleAllSelection() {
  if (isAllSelected.value) {
    // 取消当前页所有选择
    displayedProjects.value.forEach(project => {
      if (isProjectSelected(project.id)) {
        selectedProjects.value = selectedProjects.value.filter(p => p.id !== project.id)
      }
    })
  } else {
    // 选择当前页所有项目
    displayedProjects.value.forEach(project => {
      if (!isProjectSelected(project.id)) {
        selectedProjects.value.push(project)
      }
    })
  }
}

function clearSelection() {
  selectedProjects.value = []
}

function exportSelectedProjects() {
  if (selectedProjects.value.length === 0) {
    alert('请至少选择一个项目')
    return
  }
  
  console.log('导出选中的项目:', selectedProjects.value)
  // TODO: 实现导出功能
  alert(`已选择 ${selectedProjects.value.length} 个项目准备导出，功能开发中...`)
}

// 切换高级筛选显示
function toggleAdvancedFilters() {
  showAdvancedFilters.value = !showAdvancedFilters.value
}

// 重置筛选条件
function resetFilters() {
  filters.value = {
    name: '',
    projectCode: '',
    projectNumber: '',
    location: '',
    status: '',
    phaseStatus: '',
    investmentRange: '',
    startDateFrom: '',
    startDateTo: '',
    endDateFrom: '',
    endDateTo: '',
    designUnit: '',
    constructionUnit: '',
    usingUnit: '',
    biddingMode: '',
    taskDocumentNo: '',
    planningType: '',
    constructionType: '',
    requiredCompletionDateFrom: '',
    requiredCompletionDateTo: '',
    usingUnitType: ''
  }
  applyFilters()
}

// 生命周期钩子
onMounted(async () => {
  await Promise.all([fetchProjects(), fetchSettings()])
})
</script>

<style scoped>
.badge {
  padding: 0.5em 0.75em;
  font-weight: 500;
}

.bg-success {
  background-color: #28a745 !important;
}

.bg-warning {
  background-color: #ffc107 !important;
  color: #212529 !important;
}

.bg-danger {
  background-color: #dc3545 !important;
}

.bg-info {
  background-color: #17a2b8 !important;
}

.bg-primary {
  background-color: #007bff !important;
}

.bg-secondary {
  background-color: #6c757d !important;
}

.table th, .table td {
  vertical-align: middle;
  padding: 0.75rem 0.5rem;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.table th {
  font-weight: 600;
}

.card.flex-grow-1 {
  flex: 1 1 auto;
  min-height: 500px;
}

.table-responsive.flex-grow-1 {
  flex: 1 1 auto;
  min-height: 400px;
}

.table {
  border-collapse: separate;
  border-spacing: 0;
}

.table thead th {
  border-top: none;
  border-bottom: 2px solid #dee2e6;
  font-weight: 600;
}

.project-row {
  cursor: pointer;
  transition: background-color 0.2s;
}

.project-row:hover {
  background-color: rgba(0, 123, 255, 0.05);
}

.action-cell {
  position: relative;
  z-index: 2;
  padding: 0.5rem !important;
}

.action-buttons {
  display: flex;
  gap: 0.5rem;
  justify-content: flex-start;
}

.action-btn {
  position: relative;
  z-index: 3;
  font-size: 0.85rem;
  padding: 0.375rem 0.75rem;
  white-space: nowrap;
}

@media (max-width: 1400px) {
  .action-btn {
    padding: 0.375rem 0.5rem;
    font-size: 0.8rem;
  }
}

@media (max-width: 1200px) {
  .action-buttons {
    flex-direction: column;
    gap: 0.25rem;
  }
  
  .action-btn {
    width: 100%;
  }
}

.checkbox-cell {
  width: 40px;
  max-width: 40px;
  padding-left: 1rem !important;
}

.form-check {
  margin: 0;
}

.form-check-input {
  cursor: pointer;
}

.batch-actions {
  display: flex;
  align-items: center;
}
</style> 